package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  报修记录
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/repair/record")//url:模块/资源/{}/细分
public class RepairRecordController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private RepairRecordService repairRecordService;
    @Resource
    private EstateRepairAssistService recordAssistService;
    @Resource
    private RepairRecordImgService repairRecordImgService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private EstateUserService estateUserService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private LockTemplate lockTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    /**
     *  测试
     * @return
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0L;

            RepairRecord record = repairRecordService.findById(record_id);
            wxTemplateService.sendWxMsgRepair(record,0);

//            sendWxMsg(record, 1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 上报报修
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            RepairRecord repairRecord = repairRecordService.getRepairById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修工单不存在"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", repairRecord),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 报修详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail/new")
    public JSONObject detailNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/add/new 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            RepairRecord repairRecord = repairRecordService.getRepairById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修工单不存在"),true,true);
            }


            map.put("record", repairRecord);

            List<EstateUser> estateUsers = estateUserService.getEstateAndDeptByUser(record_id, user.getSysUserId(), repairRecord.getEstateId());
            map.put("estateUsers", estateUsers);


            int isCanPick = 0;
            EstateUser estateUser = estateUserService.getEstateByUser(user_id, repairRecord.getEstateId());
            if(estateUser != null){
                isCanPick = 1;
            }
            map.put("isCanPick", isCanPick);

            List<EstateRepairAssist> assistList = recordAssistService.selectListByColumn("record_id", record_id);
            map.put("assistList", assistList);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 上报报修
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : null;

            int record_type = jsonRequest.containsKey("record_type") ? jsonRequest.getInt("record_type") : 0;
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            int check_type = jsonRequest.containsKey("check_type") ? jsonRequest.getInt("check_type") : 0;
            String room_no = jsonRequest.containsKey("room_no") ? jsonRequest.getStr("room_no") : "";
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateRoom room = estateRoomService.findById(room_id);
//            if(room == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该住户不存在"),true,true);
//            }

            RepairRecord repairRecord = new RepairRecord();
            repairRecord.setUserId(user_id);
            repairRecord.setRecordType(record_type);
            repairRecord.setNickName(user.getNickName());
            repairRecord.setCreateTime(new Date());
            repairRecord.setContent(content);
            repairRecord.setState(0);
            repairRecord.setPhoneNum(phone_num);
            repairRecord.setEstateId(estate_id);
            if(room != null){
                repairRecord.setEstateId(room.getEstateId());
                repairRecord.setRoomNo(room.getRoomNo());

                Estate estate = estateService.findById(room.getEstateId());
                if(estate!=null){
                    repairRecord.setPropertyId(estate.getPropertyId());
                    repairRecord.setEstateName(estate.getEstateName());
                }
            }else{
                repairRecord.setRoomNo(room_no);
            }


            if(estate_id > 0){
                Estate estate = estateService.findById(estate_id);
                if(estate!=null){
                    repairRecord.setEstateId(estate_id);
                    repairRecord.setPropertyId(estate.getPropertyId());
                    repairRecord.setEstateName(estate.getEstateName());
                }
            }

            repairRecord.setCheckType(check_type);
            repairRecord.setOpState(0);
            //拾取方式  0 -  经理派单  1 - 自由抢单
            // 当前默认 自由抢单方式
            repairRecord.setPickType(1);


            int ret = repairRecordService.addRecord(user,repairRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功", ret),true,false);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 删除我的报修
     * @param
     * @throws Exception
     */
    @PostMapping(value="/delete")
    public JSONObject deleteRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报事不存在"),true,true);
            }

            if(repairRecord.getUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报事不属于您，暂无删除权限"),true,true);
            }

            if(repairRecord.getState() > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不允许删除"),true,true);
            }

            repairRecord.setIsDel(1);
            repairRecord.setDelTime(new Date());
            boolean ret = repairRecordService.updateById(repairRecord);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,true);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 我的上报列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateUser(user_id);

            List<RepairRecord> list = repairRecordService.selectByUserId(user_id, estateUser,state, pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 物业经理 和 维修人员的 处理列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/opUser/list")
    public JSONObject repairList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您不是管理员"),true,true);
            }


            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            List<RepairRecord> list = repairRecordService.selectEstateByUserId(user_id,sysUser,estateUser, state,pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 抢单中心的 列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/pick/list")
    public JSONObject pickList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }


            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            List<RepairRecord> list = repairRecordService.selectByEstateId(estateUser.getEstateId(), state,pageIndex,pageSize);


            map.put("records", list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我抢到的 报事报修列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/my/pick/list")
    public JSONObject myPickList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            List<RepairRecord> list = repairRecordService.selectMyPickList(user_id,sysUser,estateUser, state,pageIndex,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  指派维修师傅
     * @param
     * @throws Exception
     */
    @PostMapping(value="/setWorker")
    public JSONObject setWorker(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            int worker_id = jsonRequest.containsKey("worker_id") ? jsonRequest.getInt("worker_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修信息不存在"),true,true);
            }
            repairRecord.setOpWorkerId(worker_id);
            repairRecord.setEsManagerResult(content);
            int ret = repairRecordService.setWorker(user,repairRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功",repairRecord.getId()),true,false);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  抢单操作
     * @param
     * @throws Exception
     */
    @PostMapping(value="/pickOp")
    public JSONObject pickOp(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();

        if(StrUtil.isEmpty(requestParam)){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
        }
        logBefore(logger, "repair/record/pickOp 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
        final LockInfo lockInfo = lockTemplate.lock(user_id + "_pickOp_" + record_id, 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请绑定工作人员手机号"),true,true);
            }

            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修信息不存在"),true,true);
            }

            if(repairRecord.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已被其他人抢走啦~"),true,true);
            }


            int ret = repairRecordService.pickOp(user, sysUser, estateUser, repairRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"抢单成功"),true,false);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"抢单失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     * 处理报修，上传维修结果上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/handle")
    public JSONObject handleRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/handle 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请绑定工作人员手机号"),true,true);
            }

            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修信息不存在"),true,true);
            }
//            repairRecord.setOpResult(content);

            int ret = repairRecordService.handleRecord(user, sysUser, estateUser, content,repairRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功",ret),true,false);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 业主 评价
     * @param
     * @throws Exception
     */
    @PostMapping(value="/appraiseOp")
    public JSONObject appraiseOp(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/appraiseOp 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;
            int star = jsonRequest.containsKey("star") ? jsonRequest.getInt("star") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修信息不存在"),true,true);
            }

            repairRecord.setAppraiseContent(content);
            repairRecord.setRateStar(star);
            repairRecord.setAppraiseTime(new Date());

            int ret = repairRecordService.appraiseOp(user, content,repairRecord);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"感谢您的评价，祝您生活愉快~"),true,false);
            }else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"评价失败，请重试"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加协助人员
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addAssist")
    public JSONObject addAssist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "repair/record/appraiseOp 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            JSONArray sysUserIds = jsonRequest.containsKey("sysUserIds") ? jsonRequest.getJSONArray("sysUserIds") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            RepairRecord repairRecord = repairRecordService.findById(record_id);
            if(repairRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该报修信息不存在"),true,true);
            }

            if(repairRecord.getState() != 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不允许添加协助人员"),true,true);
            }

            if(repairRecord.getOpWxUserId() == null || repairRecord.getOpWxUserId() != null && repairRecord.getOpWxUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无添加权限"),true,true);
            }

            int ret = recordAssistService.addAssist(record_id, sysUserIds);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功"),true,true);
            } else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 报修记录的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("record_id") int record_id,@RequestParam(value = "info_id", required = false) int info_id, @RequestParam("img_type") int img_type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            RepairRecord record = repairRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    String imgs = "";
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_REPAIR_RECORD_PHOTOS;

                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date()) + "/" + fileName;

                                        String filePath1 = OssUtil.getUploadPrefix(upload_type) + DateUtil.getMonthStr(new Date());
                                        File file = new File(uploadPath + filePath1);
                                        if(!file.exists()){
                                            file.mkdirs();
                                        }

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();
                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certurl.getInputStream(),DateUtil.getMonthStr(new Date()) + "/" + fileName,upload_type);

                                        RepairRecordImg img = new RepairRecordImg();
                                        img.setImgUrl(img_key);
                                        img.setRecordId(record_id);
                                        img.setInfoId(info_id);
                                        img.setSort(1);
                                        img.setImgType(img_type);
                                        img.setPrefix(prefix);
                                        repairRecordImgService.save(img);

                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
